let ws = require("ws");

class WebsocketClient{
	constructor(name, url){
		this.name = name;
		this.url = url;
		this.state = 0;
	}
	startWork(connectCallback, errorCallback, recvCallback, closeCallback){
		this.socket = new ws(this.url);
		this.state = 1;
		let self = this;
		this.socket.on("open", function () {
			if (global.log) {
                global.log.print(`${self.name} connect success`);
            } else {
                console.log(`${self.name} connect success`);
            }
			self.state = 2;
			if (connectCallback) {
				connectCallback(this);
			}
		});
		this.socket.on("close", function() {
			if (global.log) {
                global.log.print(`${self.name} close`);
            } else {
                console.log(`${self.name} close`);
            }
			self.state = 0;
			if (closeCallback) {
				closeCallback(this);
			}
		});
		this.socket.on("error", function(err) {
			if (global.log) {
                global.log.error(`${self.name} error ${err}`);
            } else {
                console.error(`${self.name} error ${err}`);
            }
			if (errorCallback) {
				errorCallback(this, err);
			}
		});
		this.socket.on("message", function(data) {
			// console.log(data);
			if (recvCallback) {
				recvCallback(this, data);
			}
		});
	}
	send(data){
		if (this.state==2) {
			try {
				this.socket.send(data);
				return true;
			} catch (err) {
				if (global.log) {
					global.log.error(`${this.name} error ${err}`);
				} else {
					console.error(`${this.name} error ${err}`);
				}
				return false;
			}
		}
		return false;
	}
}

module.exports = WebsocketClient;